package jobs;

import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.photos.AlbumFeed;
import com.google.gdata.data.photos.PhotoEntry;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import models.PicasaAlbum;
import models.PicasaPhoto;
import play.Play;
import play.cache.Cache;
import play.jobs.Job;
import siena.PersistenceManager;
import siena.PersistenceManagerFactory;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Cyril
 * Date: 07.08.11
 * Time: 17:07
 * To change this template use File | Settings | File Templates.
 */
public class AlbumUpdateJob extends Job {
    private static final String photosUrl = "https://picasaweb.google.com/data/feed/api/user/%s/albumid/%s";
    private static final String loadJobName = "load-job-%s";

    private String albumId = null;

    public AlbumUpdateJob(String albumId) {
        this.albumId = albumId;
    }

    @Override
    public void doJob() throws Exception {
        Cache.set(getLoadJobName(albumId), true);

        PicasaAlbum album = new PicasaAlbum();
        album.id = Long.valueOf( PicasaPhoto.parseId(albumId) );

        List<PhotoEntry> picasaPhotos = getPicasaPhotos();
        PersistenceManager pm = PersistenceManagerFactory.getPersistenceManager(PicasaPhoto.class);
        for (PhotoEntry picasaPhoto : picasaPhotos) {
            PicasaPhoto photo = PicasaPhoto.getFromEntry( picasaPhoto );
            photo.album = album;
            pm.update(photo);
        }

        Cache.delete(getLoadJobName(albumId));
    }

    @Override
    public void onException(Throwable e) {
        Cache.delete(getLoadJobName(albumId));
        super.onException(e);
    }

    protected List<PhotoEntry> getPicasaPhotos() throws IOException, ServiceException {
        PicasawebService myService = getService();
        URL feedUrl = new URL(String.format(photosUrl,
                Play.configuration.getProperty("sakura.picasa.login", null),
                albumId
        ));
        AlbumFeed albumFeed = myService.getFeed(feedUrl, AlbumFeed.class);
        return albumFeed.getPhotoEntries();
    }

    protected static PicasawebService getService() throws AuthenticationException {
        PicasawebService myService = new PicasawebService( "exampleCo-exampleApp-1");
        myService.setUserCredentials(
                Play.configuration.getProperty("sakura.picasa.login"),
                Play.configuration.getProperty("sakura.picasa.pass")
        );
        return myService;
    }

    public static String getLoadJobName(String name) {
        return String.format(loadJobName, name);
    }

}
